package org.cy.evolution.ioc.context;

import org.cy.evolution.ioc.factory.EvolutionComponent;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("unchecked")
public final class ComponentContext<T> extends AbstractContext {

    private static final String SUFFIX = "Component";

    private Map<String, T> components = new HashMap<>(0);

    @Override
    public T get(String className) {
        String componentName = className + SUFFIX;
        T component = components.get(componentName);
        if (null == component) {
            Class<?> builderClass = findBuilderClass(componentName);
            if(null != builderClass) {
                try {
                    EvolutionComponent.Builder builder = (EvolutionComponent.Builder) builderClass.newInstance();
                    component = (T) builder.create().get();
                    components.put(componentName, component);
                } catch (InstantiationException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return component;
    }
}
